/*
* webSocket工具类
* @param path: webSocket地址
* @param name: webSocket名称
*/
class WebSocketUtil {

  constructor (socketJson) {
    this.path = socketJson.path;
    this.name = socketJson.name;
    this.socket = null
    this.setTime = null
    this.isRelink = 1
    this.socketNum = 0
    this.socketTime = null
    this.init()
  }

  init () {
    // 初始化前判断是否存在socket，存在则关闭
    this.socket && this.socket.onclose()
    this.socket = new WebSocket(process.env.VUE_APP_SOCKET_ADDR+this.path)
    this.socket.onopen = (jsonData) => {
      this.open(this.name, jsonData)
      //如果连接成功，则每隔2秒发送一次心跳包
      if (this.socketTime) {
        clearInterval(this.socketTime)
      }
      this.socketTime = setInterval(() => {
        this.socket.send('111')
      }, 2000)
    }
    this.socket.onmessage = (jsonData) => {
      //如果获取到消息，心跳检测重置
      if (jsonData.data === '111' || jsonData.data === 'onOpen success') {
        this.socketNum = 0
        return
      }
      this.message(this.name, jsonData)
    }
    //关闭事件
    this.socket.onclose = (jsonData) => {
      if (this.socketTime) {
        clearInterval(this.socketTime)
      }
      this.close(this.name, jsonData)
    }
    this.parse()
  }

  parse () {
    if (this.setTime) {
      clearInterval(this.setTime)
    }
    this.setTime = setInterval(() => {
      if (this.socketNum > 10) {
        this.socketError(this.name, '连接超时')
        if (this.isRelink === 0) {
          clearInterval(this.setTime)
          clearInterval(this.socketTime)
          this.socketError(this.name, '连接断开')
        } else {
          this.socketNum = 6
          if (this.socketTime) {
            clearInterval(this.socketTime)
          }
          this.init()
        }
      }
      this.socketNum++
    }, 2000)
  }

  open (name, jsonData) {

  }

  message (name, jsonData) {

  }

  close (name, jsonData) {

  }

  socketError (name, jsonData) {

  }

  stop () {
    this.socketNum = 0
    clearInterval(this.setTime)
    clearInterval(this.socketTime)
    this.socket.close()
  }
}
export default WebSocketUtil
